# -*- coding: utf-8 -*-
from openerp.osv import fields,osv
from openerp import tools
from openerp.tools.translate import _
from openerp.modules.registry import RegistryManager
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT
import datetime
from dateutil.relativedelta import relativedelta

class pm_customer_checkin(osv.osv):
    _name = 'pm.customer.checkin'

    def testmethod(self,cr,uid,ids,context=None):
        print 'call testmethod'
    
        
    def create(self,cr,uid,data,context=None):
        room_id = data['room_id']
        room = self.pool.get('pm.project.building.room').read(cr,uid,room_id,['hourseholder'],context=context)
        if room['hourseholder']:
            raise osv.except_osv(_('已经存在收费用户'),_('此房间已经存在收费对象，请先执行迁出操作！'))
                        
        values = {
            'hourseholder':data['partner_id'],
            'is_charge':True,
            'in_start_date':data['in_start_date'],
            'in_end_date':data['receive_end_date'],
            'closing_date':data['closing_date'],
        }
        
        cost_values = {
            'billing_start_date':data['receive_start_date'],
            'billing_end_date':data['receive_end_date']
        }
        print 'cost_values is %s' %  cost_values
        
        self.pool.get('pm.project.building.room').write(cr,uid,room_id,values,context=context)
        cost_item_ids = self.pool.get('pm.cost.item.room').search(cr,uid,[('room_id','=',room_id)],context=context)  
        self.pool.get('pm.cost.item.room').write(cr,uid,cost_item_ids,cost_values,context=context)
        id = super(pm_customer_checkin, self).create(cr, uid, data, context=context)        
        return id
    
    _columns = {
        'name':fields.char(string='编号',size=100),
        'project_id':fields.many2one('pm.project',string='所属管理处'),
        'area_id':fields.many2one('pm.project.area',string='所属区域',domain="[('project_id','=',project_id)]"),
        'building_id':fields.many2one('pm.project.building',string='所属楼栋',help='Building',domain="[('project_area_id','=',area_id)]"),
        'room_id':fields.many2one('pm.project.building.room','房间'),
        'receive_object':fields.selection([('owner','业主'),('rent','租户'),('no','无')],string='收费服务对象'),
        'operation_type':fields.selection([('manual','人工'),('contractin','合同自动迁入')],string='操作类型'),
        'partner_id':fields.many2one('res.partner',string='客户'),
        'house_state':fields.many2one('pm.parameter',string='迁入房间后状态',domain="[('category_code','=','FJZT')]"),
        'receive_start_date':fields.date(string='收费开始日期'),
        'receive_end_date':fields.date(string='收费结束日期'),
        'closing_date':fields.date(string='接房日期'),
        'in_start_date':fields.date(string='入住日期'),
        'input_man':fields.many2one('res.users',string='录入人'),
        'input_time':fields.datetime(string='录入时间'),
        'remark':fields.text(string='备注'),
    }
    
    _defaults = {
        'input_man': lambda self,cr,uid,ids,context=None:uid,
        'input_time':lambda self,cr,uid,ids: datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    }
pm_customer_checkin()


class pm_customer_checkout(osv.osv):
    _name = 'pm.customer.checkout'
    
    def change_room(self,cr,uid,ids,room_id,context=None):
        room = self.pool.get('pm.project.building.room').read(cr,uid,room_id,[],context=context)
        return { 'value':{
                    'partner_id':room['hourseholder'],
                    'current_receive_object':room['receive_object']
                }
        }
        

    def create(self,cr,uid,data,context=None):
        room_id = data['room_id']

        room_rep = self.pool.get('pm.project.building.room')
        room_cost_rep = self.pool.get('pm.cost.item.room')
        receive_rep = self.pool.get('pm.cost.receivable')

        room_item = room_rep.browse(cr,uid,room_id,context=context)

        sql = """select pt.id,pm.id as cost_room_item_id,pm.room_id,pt.billing_type,pt.charge_type,pt.charge_mode,pm.price,pt.unit_of_period,
        pm.charge_period,pm.billing_start_date,pm.billing_end_date,ppm.hourseholder from pm_cost_item as pt 
        inner join pm_cost_item_room as pm
        on pt.id = pm.cost_item_id
        inner join pm_project_building_room as ppm
        on pm.room_id = ppm.id
        where pt.billing_type <>'meter_reading' and pt.charge_type='normal' 
            and pt.charge_mode='period' and pm.is_charge = 'True'
            and pm.room_id = %s 
            and ppm.hourseholder=%s"""
        cr.execute(sql,(data['room_id'],data['partner_id']))
        items = cr.dictfetchall()
        print 'fetchone is %s ' % items
        checkout_date = data['checkout_date']
        
        for item in items:
            receive_rep.create_for_out(cr,uid,None,room_id,data['partner_id'],item['id'],
                                       checkout_date,context=context)
        #rec_ids = receive_rep.search(cr,uid,[('state','=','recorded'),('room_id','=',room_id)], context=context)
        #if rec_ids:
        #    raise osv.except_osv(_('费用未结算'),_('此房间仍有费用没有结算完毕，不能迁出！'))
        
        hourseholder = None
        is_charge = False
        
        room_values = {'is_charge':is_charge,'hourseholder':hourseholder,
                       'in_start_date':None,'in_end_date':None}
        if data['receive_object']=='owner':
            hourseholder = room_item.property_owner.id        
            room_values['billing_start_date'] = checkout_date
            room_values['billing_end_date'] = None

        self.pool.get('pm.project.building.room').write(cr,uid,room_id,room_values,context=context)
        if data['auto_clear_leftamout']:
            rec_ids = self.pool.get('pm.cost.receivable').search(cr,uid,[('room_id','=',room_id),('partner_id','=',room_item.hourseholder.id)],context=context)
            self.pool.get('pm.cost.receivable').write(cr,uid,rec_ids,{'current_left_amount':0.0},context=context)
        id = super(pm_customer_checkout, self).create(cr, uid, data, context=context)        
        return id

    _columns = {
        'name':fields.char(string='编号',size=100),
        'project_id':fields.many2one('pm.project',string='所属管理处'),
        'area_id':fields.many2one('pm.project.area',string='所属区域',domain="[('project_id','=',project_id)]"),
        'building_id':fields.many2one('pm.project.building',string='所属楼栋',help='Building',domain="[('project_area_id','=',area_id)]"),
        'room_id':fields.many2one('pm.project.building.room','房间'),
        'partner_id':fields.many2one('res.partner',string='原客户名称'),
        'current_receive_object':fields.selection([('owner','业主'),('no','无')],string='当前收费服务对象'),
        'receive_object':fields.selection([('owner','业主'),('no','无')],string='迁出后收费服务对象'),
        'checkout_date':fields.date(string='迁出日期'),
        'hourse_state':fields.many2one('pm.parameter',string='迁出房间后状态',domain="[('category_code','=','FJZT')]"),
        'auto_clear_leftamout':fields.boolean(string='自动结清余额'),
        'input_man':fields.many2one('res.users',string='录入人'),
        'input_time':fields.datetime(string='录入时间'),
        'remark':fields.text(string='备注'),
    }
    _defaults = {     
        'input_man': lambda self,cr,uid,ids,context=None:uid,
        'input_time':lambda self,cr,uid,ids: datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    }    
pm_customer_checkout()

class pm_customer_contract(osv.osv):
    _name = 'pm.customer.contract'
    
    def bt_check(self,cr,uid,ids,context=None):

        for data in self.read(cr,uid,ids,[],context=context):
            room = self.pool.get('pm.project.building.room').read(cr,uid,data['room_id'][0],context=context)
            if room['hourseholder']:
                raise osv.except_osv("激活失败","当前房间仍然存在收费对象，请先将些房间的收费对象迁出!")
            print 'data is %s' % data
            in_item = data
            in_item['project_id'] = data['project_id'][0]
            in_item['building_id'] = data['building_id'][0]
            in_item['area_id'] = data['area_id'][0]
            in_item['room_id'] = data['room_id'][0]
            in_item['receive_object'] = 'rent'
            in_item['operation_type'] = 'contractin'
            in_item['partner_id'] = data['partner_id'][0]
            in_item['receive_start_date'] = data['start_date']
            in_item['receive_end_date'] = data['end_date']
            in_item['in_start_date'] = data['start_date']
            in_item['closing_date'] = None
            in_item['input_time'] = None
            in_item['input_man'] = uid
            if self.pool.get('pm.customer.checkin').create(cr,uid,in_item,context=context):
                self.write(cr,uid,data['id'],{'state':'active'},context=context)
        return True

    def attachment_tree_view(self, cr, uid, ids, context):
        domain = [
             '&', ('res_model', '=', 'pm.customer.contract'), ('res_id', 'in', ids),
        ]
        res_id = ids and ids[0] or False
        return {
            'name': _('Documents'),
            'domain': domain,
            'res_model': 'ir.attachment',
            'type': 'ir.actions.act_window',
            'view_id': False,
            'view_mode': 'tree,form',
            'view_type': 'form',
            'limit': 80,
            'context': "{'default_res_model': '%s','default_res_id': %d}" % (self._name, res_id)
        }

    def get_contract_attaments(self,cr,uid,ids,field_name,args,context=None):
        res = {}
        for id in ids:
            temp = self.pool.get('ir.attachment').search(cr,uid,[('res_model','=','pm.customer.contract'),('res_id','=',id)],context=context)
            res[id] = temp
        return res

    def _get_left_days(self,cr,uid,ids,field_name,args,context=None):
        res = {}
        for item in self.read(cr,uid,ids,['id','end_date'],context=context):
            end_date = datetime.datetime.strptime(item['end_date'],DATE_FORMAT)
            start_date = datetime.datetime.now()
            #a = relativedelta(end_date,start_date)
            #print 'start,end,del is %s,%s,%s' % (start_date,end_date,a)
            days = (end_date - start_date).days
            res[item['id']] = days>0 and days or 0
        print 'res is %s' % res
        return res

    def change_start_and_end_date(self,cr,uid,ids,start_date,end_date,context=None):
        values = {}
        start_date = datetime.datetime.strptime(start_date,DATE_FORMAT)
        end_date = datetime.datetime.strptime(end_date,DATE_FORMAT)
        values['total_days'] = (end_date-start_date).days
        return {'value':values}

    def create(self,cr,uid,data,context=None):
        if self.search(cr,uid,[('room_id','=',data['room_id']),('state','!=','end')],context=context):
            raise osv.except_osv(_('不要重复提交'),_('此房间已经存在合同，请不要重复提交或者先终止现有合同！'))
        super(pm_customer_contract,self).create(cr,uid,data,context=context)
        
    _columns = {
        'project_id':fields.many2one('pm.project',string='所属管理处'),
        'area_id':fields.many2one('pm.project.area',string='所属区域',domain="[('project_id','=',project_id)]"),
        'building_id':fields.many2one('pm.project.building',string='所属楼栋',help='Building',domain="[('project_area_id','=',area_id)]"),
        'room_id':fields.many2one('pm.project.building.room','房间'),
        'name':fields.char(string='合同编号',size=100),
        'partner_id':fields.many2one('res.partner',string='选择租户'),
        'rent_partner_id':fields.many2one('res.partner',string='出租方'),
        'legal_person':fields.char(string='法定代表',size=100),
        'contact_person':fields.char(string='联系人',size=100),
        'start_date':fields.date(string='起租日期',required=True),
        'end_date':fields.date(string='停租日期',required=True),
        'sign_date':fields.date(string='签约日期'),
        'total_days':fields.integer(string='总天数'),
        'left_days':fields.function(_get_left_days,type='integer',string='剩余天数'),
        'rent_month':fields.integer(string='租期(月)'),
        'contract_amount':fields.float(string='合同总额'),
        'rent_use':fields.char(string='租赁用途',size=300),
        'rent_area':fields.float(string='收费面积'),
        'protect_amount':fields.float(string='保证金'),
        'protect_amount_remark':fields.text(string='保证金说明'),
        'agence_fee_amount':fields.float(string='中介费'),
        'payment_method':fields.char(string='付款方式',size=100),
        'contract_address':fields.char(string='合同地点',size=300),
        'contract_terms':fields.text(string='合同条款'),
        'additional_terms':fields.text(string='附加条款'),
        'remark':fields.text(string='合同备注'),
        'contract_attachments':fields.function(get_contract_attaments,type='one2many',relation='ir.attachment',string='合同附件'),
        'input_man':fields.many2one('res.users',string='录入人'),
        'input_time':fields.datetime(string='录入时间'),
        'end_time':fields.date(string='终止日期'),
        'state':fields.selection([('notactive','未生效'),('active','已生效'),('end','已终止')],string='合同状态'),
    }
    
    _defaults = {     
        'input_man': lambda self,cr,uid,ids,context=None:uid,
        'input_time':lambda self,cr,uid,ids: datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S'),
        'sign_date':lambda self,cr,uid,ids: datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d'),        
        'state':lambda self,cr,uid,ids,context=None: 'notactive',
        'rent_month':12,
    }  
pm_customer_contract()

class res_partner(osv.osv):
    _inherit = 'res.partner'
    _columns = {
        'is_owner':fields.boolean(string='业主'),
        'is_rent':fields.boolean(string='租户'),
        'is_third':fields.boolean(string='外协单位'),
        'third_type':fields.many2one('pm.parameter',string='外协单位类别'),
    }
res_partner()
